%% Author: John
%% Created: 2010-6-27
%% Description: TODO: Add description to socket_example

-module(socket_example).

%%
%% Include files
%%

%%
%% Exported Functions

%%
-export([nano_get_url/0]).

%%
%% API Functions
%%
%% gen_tcp:connect(Host, 80, [binary,{packet,0}])
%% binary:以binary模式打开套接字
%% {packet,0}：Erlang系统会把TCP数据原封不动的直接传送给应用程序
%% 当程序收到一个{tcp_closed,Socket}消息的时候,表明web服务器已经停止向程序发送数据.http/1.0协议是这样的
%%
%% TODO: Add description of nano_get_url/function_arity
%%
nano_get_url() -> 
	nano_get_url("www.google.com").



%%
%% Local Functions
%%
nano_get_url(Host)->
	{ok,Socket}=gen_tcp:connect(Host, 80, [binary,{packet,0}]),
	ok=gen_tcp:send(Socket, "GET / HTTP/1.0\r\n\r\n"),
	receive_data(Socket,[]).

receive_data(Socket,SoFar)->
	receive
		{tcp,Socket,Bin}->
			receive_data(Socket,[Bin|SoFar]);
		{tcp_closed,Socket}->
			string:tokens(binary_to_list(list_to_binary(lists:reverse(SoFar))),"\r\n")
	end.
	
	
	
